package com.lanou.musicbox.fragment.onlinemusic;

import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.lanou.musicbox.R;
import com.lanou.musicbox.adapter.onlinemusic.RecommendListViewAdapter;
import com.lanou.musicbox.adapter.onlinemusic.RecommendViewPager;
import com.lanou.musicbox.adapter.onlinemusic.RecommendstationAdapter;
import com.lanou.musicbox.adapter.onlinemusic.RemmendGridViewAdapter;
import com.lanou.musicbox.base.BaseFragment;
import com.lanou.musicbox.bean.Recommend;
import com.lanou.musicbox.bean.RecommendStation;
import com.lanou.musicbox.bean.Recommendsongs;
import com.lanou.musicbox.bean.RecommentSongsMenu;
import com.lanou.musicbox.custom.Events;
import com.lanou.musicbox.entity.Entity;
import com.lanou.musicbox.utils.Contant;
import com.lanou.musicbox.utils.NetWorkUtils;
import com.lanou.musicbox.utils.StringRequestUtf;
import com.lanou.musicbox.utils.VolleySingleton;

import java.util.ArrayList;
import java.util.List;

import de.greenrobot.event.EventBus;


/**
 * Created by 杨海宁 on 15/10/20.
 * 网络音乐_推荐页面
 */
public class RecommendFragment extends BaseFragment
        implements View.OnClickListener, ViewPager.OnPageChangeListener {
    /**
     * 轮播数据
     **/
    private ViewPager viewPager;
    private ArrayList<Recommend.PicEntity> data = new ArrayList<>();
    private RecommendViewPager adapter;
    /**
     * 歌单数据
     */
    private GridView recommend_gridview;
    private ArrayList<RecommentSongsMenu.ContentEntity.ListEntity> listdata = new ArrayList<>();
    private RemmendGridViewAdapter gridViewAdapter;
    private RecommentSongsMenu.ContentEntity listEntity;
    /***
     * 歌曲推荐数据
     */
    private ListView recommend_listview;
    private ArrayList<Recommendsongs.ContentEntity.SongListEntity> songsdata = new ArrayList<>();
    private Recommendsongs.ContentEntity contentEntity;
    private RecommendListViewAdapter listViewAdapter;
    /**
     * 电台推荐
     */
    private GridView station_gridview;
    private ArrayList<RecommendStation.ListEntity> stationdata = new ArrayList<>();
    private RecommendstationAdapter stationAdapter;
    private VolleySingleton volleySingleton;//定义个volleysingletion属性
    private StringRequestUtf requestUtf;
    private Handler handler;//定义个handler属性
    private Handler startHandle;
    private HandlerThread handlerThread;
    private boolean Flag;
    private int current = 0;
    private TextView songs_more, station_more;
    private LinearLayout viewPicture;
    private ProgressDialog dialog;
    private boolean isConnect;



    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.recommned_viewpager, null);
        viewPager = (ViewPager) view.findViewById(R.id.recommend_viewpager);
        recommend_gridview = (GridView) view.findViewById(R.id.recommend_gridview);
        recommend_listview = (ListView) view.findViewById(R.id.recommend_listview);
        station_gridview = (GridView) view.findViewById(R.id.station_gridview);
        viewPicture = (LinearLayout) view.findViewById(R.id.viewPicture);
        songs_more = (TextView) view.findViewById(R.id.songs_more);
        station_more = (TextView) view.findViewById(R.id.station_more);
        songs_more.setOnClickListener(this);
        station_more.setOnClickListener(this);

        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        volleySingleton = VolleySingleton.getInstance(getActivity());

        isConnect = NetWorkUtils.checkNet(getActivity());
        dialog=new ProgressDialog(getActivity());

        initRecommendsongMenu();
        initRecommendSongs();
        initRadio();
        initdata();
        initOnItemListener();
        startHandle = new Handler();
        BackThread();
    }

    private void initOnItemListener() {
        //歌单推荐监听
        recommend_gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                FragmentManager manager = getActivity().getSupportFragmentManager();
                EnterThePlaylistFragment fragment = new EnterThePlaylistFragment();
                Bundle bundle = new Bundle();
                bundle.putString("songs_id", listEntity.getList().get(position).getListid());
                fragment.setArguments(bundle);
                FragmentTransaction transaction = manager.beginTransaction();
                transaction.addToBackStack(null);
                transaction.replace(R.id.fill_main, fragment);
                transaction.commit();

            }
        });
        //新歌推荐的监听
        recommend_listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                List<Entity> songsInfos = new ArrayList<>();
                for (int i = 0; i < songsdata.size(); i++) {
                    Entity netSongs = new Entity();
                    String song_id = songsdata.get(i).getSong_id();
                    String title = songsdata.get(i).getTitle();
                    String pic_small = songsdata.get(i).getPic_small();
                    String pic_premium = songsdata.get(i).getPic_big();
                    String author = songsdata.get(i).getAuthor();

                    netSongs.setSongs_id(song_id);
                    netSongs.setTitle(title);
                    netSongs.setSmall_pic(pic_small);
                    netSongs.setBig_pic(pic_premium);
                    netSongs.setArtist(author);
                    netSongs.setItem_id(position);
                    songsInfos.add(i, netSongs);
                }
                String whatMusic = "网络";
                Events.MusicInfoEvent musicInfoEvent = new Events.MusicInfoEvent();
                musicInfoEvent.setMp3Infos(songsInfos, whatMusic);
                EventBus.getDefault().post(musicInfoEvent);


            }
        });

    }

    //创建个解析轮播的构造方法
    private void initdata() {
        String url = Contant.Url.URL_Recommend_lunbo;
        requestUtf = new StringRequestUtf(url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Gson gson = new Gson();
                Recommend recommend = gson.fromJson(response, Recommend.class);
                if (recommend != null && recommend.getPic() != null) {
                    data = (ArrayList<Recommend.PicEntity>) recommend.getPic();
                    //  Log.i("解析出数据", data + " ");

//                for (int i = 0; i < data.size(); i++) {
//
//
//                        ImageView imageView = new ImageView(getActivity());
//                        imageView.setLayoutParams(new ViewGroup.LayoutParams(15, 15));
//                        if (i == 0) {
//                            imageView.setImageResource(R.drawable.point_nomal);
//                        } else {
//                            imageView.setImageResource(R.drawable.point_press);
//                        }
//                        viewPicture.addView(imageView);
//
//
//                }

                    

                }

                //viewpager的监听
                viewPager.setOnPageChangeListener(RecommendFragment.this);
                //初始化适配器
                adapter = new RecommendViewPager(getActivity(), data);
                viewPager.setAdapter(adapter);
                viewPager.setCurrentItem(1000);
                if (dialog.isShowing()) {
                    dialog.dismiss();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

                if (isConnect){
                    Toast.makeText(getActivity(), R.string.no_network, Toast.LENGTH_SHORT).show();
                }else{
                    Toast.makeText(getActivity(), R.string.connect_error, Toast.LENGTH_SHORT).show();
                }

           }

        });
        volleySingleton.addQueue(requestUtf);
            if (isConnect){
                dialog.setMessage("数据加载中.....");
                dialog.show();
            }




    }
    //创建个解析推荐歌单的构造方法
    private void initRecommendsongMenu() {

        String songMenuUrl = Contant.Url.URL_Recommend_songMenu;
        requestUtf = new StringRequestUtf(songMenuUrl, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {

                Gson gsons = new Gson();
                RecommentSongsMenu remmentSongs = gsons.fromJson(response, RecommentSongsMenu.class);
                listEntity = remmentSongs.getContent();

                if (listEntity != null && listEntity.getList() != null) {
                    listdata = (ArrayList<RecommentSongsMenu.ContentEntity.ListEntity>) listEntity.getList();
                    Log.i("推荐歌单", listdata + " ");
                }
                gridViewAdapter = new RemmendGridViewAdapter(getActivity(), listdata);
                recommend_gridview.setAdapter(gridViewAdapter);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
        volleySingleton.addQueue(requestUtf);
    }

    //创建个解析推荐歌曲的构造方法
    private void initRecommendSongs() {
        String songUrl = Contant.Url.URL_Recommend_song;
        requestUtf = new StringRequestUtf(songUrl, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Gson gsonss = new Gson();
                Recommendsongs songs = gsonss.fromJson(response, Recommendsongs.class);
                contentEntity = songs.getContent().get(0);
                if (contentEntity != null && contentEntity.getSong_list() != null) {
                    songsdata = (ArrayList<Recommendsongs.ContentEntity.SongListEntity>) contentEntity.getSong_list();
                    Log.i("推荐歌曲", songsdata + " ");

                }
                listViewAdapter = new RecommendListViewAdapter(getActivity(), songsdata);
                recommend_listview.setAdapter(listViewAdapter);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });

        volleySingleton.addQueue(requestUtf);


    }

    //推荐电台
    private void initRadio() {
        String stationurl = Contant.Url.URL_Recommend_Radio;
        requestUtf = new StringRequestUtf(stationurl, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Gson gsonis = new Gson();
                RecommendStation station = gsonis.fromJson(response, RecommendStation.class);
                if (station != null && station.getList() != null) {
                    stationdata = (ArrayList<RecommendStation.ListEntity>) station.getList();
                }
                stationAdapter = new RecommendstationAdapter(getActivity(), stationdata);
                station_gridview.setAdapter(stationAdapter);
            }

        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });

        volleySingleton.addQueue(requestUtf);
    }


    public void BackThread() {
        handlerThread = new HandlerThread("handler");
        handlerThread.start();//开始线程
        handler = new Handler(handlerThread.getLooper()) {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);//延迟俩秒发送一个消息
                Running();
                if (Flag) {
                    handler.sendEmptyMessageDelayed(10, 4000);
                }
            }
        };

    }

    public void Running() {
        startHandle.post(new Runnable() {
            @Override
            public void run() {
                current++;
                if (current == data.size() - 1) {
                    current = 0;
                }
                viewPager.setCurrentItem(current);
            }
        });

    }

    @Override
    public void onResume() {
        super.onResume();
        Flag = true;
        handler.sendEmptyMessage(10);
    }

    @Override
    public void onPause() {
        super.onPause();
        Flag = false;
        handler.removeMessages(10);
    }


    @Override
    public void onClick(View v) {
        String msg = "";
        switch (v.getId()) {
            case R.id.songs_more:
                msg = "one";
                break;
            case R.id.station_more:
                msg = "two";
                break;
        }
        EventBus.getDefault().post(new Events.FristEvent(msg));
    }

    /**
     * 页面正在滑动时的回调
     */
    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    /**
     * 页面切换时的回调
     */
    @Override
    public void onPageSelected(int position) {
//        for (int i = 0; i < data.size(); i++) {
//            ImageView imageView = (ImageView) viewPicture.getChildAt(i);
//            imageView.setImageResource(R.drawable.point_nomal);
//        }
//        ImageView img = (ImageView) viewPicture.getChildAt(position & data.size());
//        img.setImageResource(R.drawable.point_press);
    }

    /**
     * 页面状态发生变化时的回调
     */
    @Override
    public void onPageScrollStateChanged(int state) {

    }
}